//
//  IWOAuthViewController.m
//  SINA
//
//  Created by 王相超 on 16/3/31.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

#import "IWOAuthViewController.h"
#import <AFNetworking.h>
#import "IWAccount.h"
#import "IWTabBarController.h"
#import "AppDelegate.h"
#import "IWAccoutTool.h"

#define APP_KEY @"1137678068"
#define APP_SECRET @"11b1a04ffaa1eac2ed77bcbe5a423d23"
#define REDIRECT_URI  @"http://www.baidu.com"

@interface IWOAuthViewController ()<UIWebViewDelegate>

@end

@implementation IWOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:webView];
    
    webView.delegate = self;
    
    //加载网址
    
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",APP_KEY,REDIRECT_URI];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [webView loadRequest:request];
    
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlStr = request.URL.absoluteString;
    
    if ([urlStr hasPrefix:REDIRECT_URI]) {
        
        //http://www.baidu.com/?code=52c10ff3a895877d701d503410d67bb9
        
        NSRange range = [urlStr rangeOfString:@"code="];
        
        NSString *code = [urlStr substringFromIndex:range.location + range.length];
        
               
        [self getAcessTokenWithCode:code];
        
        return NO;
    }
    return YES;
}

//获取手机token
- (void)getAcessTokenWithCode:(NSString *)code{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *str = @"https://api.weibo.com/oauth2/access_token";
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"client_id"] = APP_KEY;
    parameters[@"client_secret"] = APP_SECRET;
    parameters[@"grant_type"] = @"authorization_code";
    parameters[@"code"] = code;
    parameters[@"redirect_uri"] = REDIRECT_URI;
   
    
    [manager POST:str parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        IWAccount *model = [[IWAccount alloc] init];
        [model setValuesForKeysWithDictionary:responseObject];
        

         //归档
        [IWAccoutTool saveAccount:model];
        
        //跳转到主页面
        IWTabBarController *tabVC = [IWTabBarController new];
        
        UIWindow *window = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
        
        window.rootViewController = tabVC;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
    
}



@end
